package middleware

import (
	"bytes"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/global"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"regexp"
	"time"
)

type BodyLogWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (w *BodyLogWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}

/**
请求时间记录
*/
func ReqTimeLog() gin.HandlerFunc {
	return func(c *gin.Context) {
		// Start timer
		start := time.Now()
		path := c.Request.URL.Path
		method := c.Request.Method
		randId := time.Now().UnixNano()
		rsp := ""
		if method == http.MethodPost || method == http.MethodPut || method == http.MethodDelete {
			c.Request.ParseForm()
			if path == "/login-pwd" {
				global.Log.Info("do not print para for login-pwd")
				global.Log.Info("randId >>> ", zap.Any("randId", randId))
				global.Log.Info("rsp >>>", zap.Any("rsp", rsp))
				//mlog.Info(randId, " > ", path, "do not print para for login-pwd", c.Params)
			} else {
				global.Log.Info(path)
				//mlog.Info(randId, " > ", path, c.Request.PostForm.Encode(), c.Params)
			}
		}
		if method == http.MethodGet {
			global.Log.Info(path)
			//mlog.Info(randId, " > ", path, c.Request.URL.Query().Encode(), c.Params)
		}
		isNotPrintRsp := true
		blw := &BodyLogWriter{}
		if isNotPrintRsp, _ = regexp.MatchString(`^/img-code|/login-pc-qq|/login-pc-qq-handler*$`, path); !isNotPrintRsp {
			blw.body = bytes.NewBufferString("")
			blw.ResponseWriter = c.Writer
			c.Writer = blw
		}
		// Process request
		c.Next()
		if !isNotPrintRsp {
			rsp = blw.body.String()
		}
		// Stop timer
		end := time.Now()
		latency := end.Sub(start)
		clientIP := c.ClientIP()
		statusCode := c.Writer.Status()
		global.Log.Info("statusCode,latency,clientIP:", zap.Any("clientIP", clientIP))
		global.Log.Info("statusCode,latency,latency:", zap.Any("latency", latency))
		global.Log.Info("statusCode,latency,statusCode:", zap.Any("statusCode", statusCode))
		//mlog.Info(randId," > ",statusCode,latency,clientIP,	method,	path,rsp,)
	}
}
